<template>
  <div class="order-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>商品订单管理</h2>
      <p>管理所有商品订单信息</p>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" clearable prefix-icon="el-icon-search"
            @keyup.enter.native="handleSearch" />
        </el-col>
        <el-col :span="6">
          <el-input v-model="searchForm.productName" placeholder="请输入商品名称" clearable prefix-icon="el-icon-search"
            @keyup.enter.native="handleSearch" />
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.status" placeholder="订单状态" clearable style="width: 100%">
            <el-option label="待付款" :value="0" />
            <el-option label="已付款" :value="1" />
            <el-option label="已发货" :value="2" />
            <el-option label="已完成" :value="3" />
            <el-option label="已取消" :value="4" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width: 100%" />
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon">
              <i class="el-icon-s-order"></i>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ totalOrders }}</div>
              <div class="stat-label">总订单数</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon">
              <i class="el-icon-money"></i>
            </div>
            <div class="stat-content">
              <div class="stat-number">¥{{ totalAmount }}</div>
              <div class="stat-label">总金额</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon">
              <i class="el-icon-warning"></i>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ pendingPaymentCount }}</div>
              <div class="stat-label">待发货</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon">
              <i class="el-icon-success"></i>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ completedCount }}</div>
              <div class="stat-label">已完成</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 订单列表 -->
    <div class="order-list">
      <div class="list-header">
        <h3>订单列表</h3>
        <div class="list-actions">
          <!-- <el-button type="success" size="small" @click="exportOrders">导出订单</el-button> -->
          <el-button type="primary" size="small" @click="refreshData">刷新</el-button>
        </div>
      </div>

      <el-table :data="orderList" v-loading="loading" stripe style="width: 100%"
        @selection-change="handleSelectionChange" :max-height="600">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="order_no" label="订单号" width="150" fixed="left">
          <template slot-scope="scope">
            <div class="order-no-container">
              <el-link type="primary" @click="viewOrderDetail(scope.row)">
                {{ scope.row.order_no }}
              </el-link>
              <el-tag v-if="scope.row.type === 2" type="warning" size="mini" class="group-tag">
                团购
              </el-tag>
              <el-tag v-if="scope.row.type === 3" type="danger" size="mini" class="seckill-tag">
                秒杀
              </el-tag>
            </div>
          </template>
        </el-table-column>

        <!-- 商品信息列 -->
        <el-table-column label="商品信息" min-width="280">
          <template slot-scope="scope">
            <div class="product-info">
              <el-image :src="scope.row.main_image" :preview-src-list="[scope.row.main_image]" fit="cover"
                class="product-image" />
              <div class="product-details">
                <div class="product-name">{{ scope.row.product_name }}</div>
                <div class="product-specs" v-if="scope.row.productList && scope.row.productList[0]">
                  <span class="spec-item" v-for="(spec, index) in parseSpecs(scope.row.productList[0].specs)"
                    :key="index">
                    {{ spec.spec_name }}: {{ spec.spec_value }}
                  </span>
                </div>
                <div class="product-price">
                  <span class="price-label">单价:</span> ¥{{ scope.row.productList && scope.row.productList[0] ?
                    scope.row.productList[0].price : '0.00' }}
                  <span class="quantity-label">数量:</span> {{ scope.row.productList && scope.row.productList[0] ?
                    scope.row.productList[0].quantity : '0' }}
                </div>
                <div class="total-amount">应付金额: ¥{{ scope.row.total_amount }}</div>
                <div class="pay-amount">实付金额: ¥{{ scope.row.pay_amount || '0.00' }}</div>
                <div class="discount-amount">减免金额: ¥{{ ((scope.row.total_amount || 0) - (scope.row.pay_amount || 0)).toFixed(2) }}</div>
              </div>
            </div>
          </template>
        </el-table-column>

        <!-- 用户信息列 -->
        <el-table-column label="用户信息" min-width="200">
          <template slot-scope="scope">
            <div class="user-info" v-if="scope.row.user">
              <div class="user-name">
                <i class="el-icon-user"></i>
                {{ scope.row.user.nickname || '未知用户' }}
              </div>
              <div class="user-mobile">
                <i class="el-icon-phone"></i>
                {{ scope.row.user.mobile || '未知手机号' }}
              </div>
              <div class="user-remark" v-if="scope.row.user.remark">
                <i class="el-icon-edit"></i>
                {{ scope.row.user.remark }}
              </div>
            </div>
            <div v-else class="user-info">
              <span class="text-muted">用户ID: {{ scope.row.user_id }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 收货地址列 -->
        <el-table-column label="收货地址" min-width="250">
          <template slot-scope="scope">
            <div class="address-info" v-if="scope.row.address">
              <div class="consignee">
                <i class="el-icon-user"></i>
                {{ scope.row.address.consignee }}
              </div>
              <div class="address-detail">
                <i class="el-icon-location"></i>
                {{ scope.row.address.province }} {{ scope.row.address.city }} {{ scope.row.address.district }}
              </div>
              <div class="address-detail">
                <i class="el-icon-house"></i>
                {{ scope.row.address.detail }}
              </div>
              <div class="mobile">
                <i class="el-icon-phone"></i>
                {{ scope.row.address.mobile }}
              </div>
            </div>
            <div v-else class="address-info">
              <span class="text-muted">地址ID: {{ scope.row.address_id }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 订单状态列 -->
        <el-table-column label="订单状态" width="120">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
            <div class="status-time" v-if="scope.row.payment_time">
              <small>付款: {{ formatDate(scope.row.payment_time) }}</small>
            </div>
          </template>
        </el-table-column>

        <!-- 是否使用优惠券列 -->
        <el-table-column label="是否使用优惠券" width="120">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.coupon_name" type="success" size="small">是</el-tag>
            <el-tag v-else type="info" size="small">否</el-tag>
          </template>
        </el-table-column>

        <!-- 优惠券列 -->
        <el-table-column label="优惠券" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.coupon_name" class="coupon-name">{{ scope.row.coupon_name }}</span>
            <span v-else class="no-coupon">无</span>
          </template>
        </el-table-column>

        <!-- 创建时间列 -->
        <el-table-column prop="created_at" label="创建时间" width="150">
          <template slot-scope="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="viewOrderDetail(scope.row)">
              查看
            </el-button>
            <el-button v-if="scope.row.status === 1" size="mini" type="warning" @click="shipOrder(scope.row)">
              发货
            </el-button>
            <el-button v-if="scope.row.status === 0" size="mini" type="danger" @click="cancelOrder(scope.row)">
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="pagination.currentPage" :page-sizes="[10]" :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="pagination.total" />
      </div>
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog title="订单详情" :visible.sync="orderDetailVisible" width="800px" :before-close="handleCloseOrderDetail">
      <div v-if="currentOrder" class="order-detail">
        <!-- 基本信息 -->
        <el-card class="detail-card" shadow="never">
          <div slot="header">
            <span><i class="el-icon-document"></i> 基本信息</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <label>订单号:</label>
                <span class="order-no">{{ currentOrder.order_no }}</span>
              </div>
              <div class="detail-item">
                <label>订单状态:</label>
                <el-tag :type="getStatusType(currentOrder.status)">
                  {{ getStatusText(currentOrder.status) }}
                </el-tag>
              </div>
              <div class="detail-item">
                <label>创建时间:</label>
                <span>{{ formatDate(currentOrder.created_at) }}</span>
              </div>
              <div class="detail-item" v-if="currentOrder.payment_time">
                <label>付款时间:</label>
                <span>{{ formatDate(currentOrder.payment_time) }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <label>总金额:</label>
                <span class="amount">¥{{ currentOrder.total_amount }}</span>
              </div>
              <div class="detail-item">
                <label>支付金额:</label>
                <span class="amount">¥{{ currentOrder.pay_amount }}</span>
              </div>
              <div class="detail-item" v-if="currentOrder.pay_trade_no">
                <label>交易号:</label>
                <span>{{ currentOrder.pay_trade_no }}</span>
              </div>
              <div class="detail-item" v-if="currentOrder.remark">
                <label>备注:</label>
                <span>{{ currentOrder.remark || '无' }}</span>
              </div>
              <div class="detail-item" v-if="currentOrder.express_company">
                <label>快递公司:</label>
                <span>{{ currentOrder.express_company }}</span>
              </div>
              <div class="detail-item" v-if="currentOrder.express_no">
                <label>快递单号:</label>
                <span class="express-no">{{ currentOrder.express_no }}</span>
                <el-button 
                  v-if="currentOrder.express_company && currentOrder.express_no"
                  size="mini" 
                  type="info" 
                  style="margin-left: 10px;"
                  @click="viewLogistics(currentOrder)"
                >
                  查看物流
                </el-button>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 商品信息 -->
        <el-card class="detail-card" shadow="never">
          <div slot="header">
            <span><i class="el-icon-goods"></i> 商品信息 ({{ currentOrder.productList ? currentOrder.productList.length : 0
            }}件)</span>
          </div>

          <!-- 商品列表 -->
          <div class="products-list" v-if="currentOrder.productList && currentOrder.productList.length > 0">
            <div class="product-item" v-for="(product, index) in currentOrder.productList" :key="index">
              <div class="product-header">
                <span class="product-index">商品 {{ index + 1 }}</span>
                <el-tag size="mini" type="info">数量: {{ product.quantity }}</el-tag>
              </div>

              <div class="product-content">
                <div class="product-image">
                  <el-image :src="product.main_image || currentOrder.main_image"
                    :preview-src-list="[product.main_image || currentOrder.main_image]" fit="cover" />
                </div>

                <div class="product-info">
                  <h4 class="product-name">{{ product.product_name }}</h4>

                  <!-- 商品规格 -->
                  <div class="product-specs" v-if="product.specs">
                    <div class="spec-item" v-for="(spec, specIndex) in parseSpecs(product.specs)" :key="specIndex">
                      <span class="spec-label">{{ spec.spec_name }}:</span>
                      <span class="spec-value">{{ spec.spec_value }}</span>
                    </div>
                  </div>

                  <!-- 价格信息 -->
                  <div class="product-price-info">
                    <div class="price-row">
                      <span class="price-label">单价:</span>
                      <span class="price-value">¥{{ product.price || '0.00' }}</span>
                    </div>
                    <div class="price-row">
                      <span class="price-label">数量:</span>
                      <span class="price-value">{{ product.quantity || '0' }}</span>
                    </div>
                    <div class="price-row total-row">
                      <span class="price-label">小计:</span>
                      <span class="price-value total-price">¥{{ (parseFloat(product.price || 0) *
                        parseInt(product.quantity
                          || 0)).toFixed(2) }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 订单总计 -->
            <div class="order-total">
              <div class="total-line">
                <span class="total-label">订单总计:</span>
                <span class="total-amount">¥{{ currentOrder.total_amount }}</span>
              </div>
              <div class="total-line" v-if="currentOrder.pay_amount !== currentOrder.total_amount">
                <span class="total-label">实付金额:</span>
                <span class="total-amount">¥{{ currentOrder.pay_amount }}</span>
              </div>
            </div>
          </div>

          <!-- 无商品信息时的提示 -->
          <div v-else class="no-products">
            <el-empty description="暂无商品信息" :image-size="80"></el-empty>
          </div>
        </el-card>

        <!-- 用户信息 -->
        <el-card class="detail-card" shadow="never" v-if="currentOrder.user">
          <div slot="header">
            <span><i class="el-icon-user"></i> 用户信息</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="detail-item">
                <label>用户ID:</label>
                <span>{{ currentOrder.user.id }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <label>昵称:</label>
                <span>{{ currentOrder.user.nickname }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <label>手机号:</label>
                <span>{{ currentOrder.user.mobile }}</span>
              </div>
            </el-col>
            <el-col :span="24" v-if="currentOrder.user.remark">
              <div class="detail-item">
                <label>备注:</label>
                <span>{{ currentOrder.user.remark }}</span>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 收货地址 -->
        <el-card class="detail-card" shadow="never" v-if="currentOrder.address">
          <div slot="header">
            <span><i class="el-icon-location"></i> 收货地址</span>
          </div>
          <div class="address-detail">
            <div class="detail-item">
              <label>收货人:</label>
              <span>{{ currentOrder.address.consignee }}</span>
            </div>
            <div class="detail-item">
              <label>手机号:</label>
              <span>{{ currentOrder.address.mobile }}</span>
            </div>
            <div class="detail-item">
              <label>详细地址:</label>
              <span>{{ currentOrder.address.province }} {{ currentOrder.address.city }} {{ currentOrder.address.district
              }}
                {{ currentOrder.address.detail }}</span>
            </div>
          </div>
        </el-card>
      </div>
    </el-dialog>

    <!-- 发货对话框 -->
    <el-dialog title="订单发货" :visible.sync="shipDialogVisible" width="500px" :before-close="closeShipDialog">
      <div class="ship-dialog">
        <!-- 订单信息 -->
        <div class="order-info" v-if="currentOrder">
          <el-descriptions :column="1" border size="small">
            <el-descriptions-item label="订单号">{{ currentOrder.order_no }}</el-descriptions-item>
            <el-descriptions-item label="商品名称">{{ currentOrder.product_name }}</el-descriptions-item>
            <el-descriptions-item label="收货人">{{ currentOrder.address ? currentOrder.address.consignee : '未知'
            }}</el-descriptions-item>
            <el-descriptions-item label="收货地址">
              {{ currentOrder.address ? `${currentOrder.address.province} ${currentOrder.address.city}
              ${currentOrder.address.district} ${currentOrder.address.detail}` : '未知' }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 快递信息表单 -->
        <div class="ship-form">
          <h4>填写快递信息</h4>
          <el-form :model="shipForm" label-width="100px" size="small">
            <el-form-item label="快递公司" required>
              <el-select v-model="shipForm.express_company" placeholder="请选择快递公司" style="width: 100%">
                <el-option label="中通快递" value="中通快递" />
                <el-option label="申通快递" value="申通快递" />
                <el-option label="圆通速递" value="圆通速递" />
                <el-option label="韵达速递" value="韵达速递" />
                <el-option label="邮政快递包裹" value="邮政快递包裹" />
                <el-option label="EMS" value="EMS" />
                <el-option label="顺丰速运" value="顺丰速运" />
                <el-option label="京东快递" value="京东快递" />
                <el-option label="京东快运" value="京东快运" />
                <el-option label="优速快递" value="优速快递" />
                <el-option label="德邦快递" value="德邦快递" />
                <el-option label="极兔速递" value="极兔速递" />
                <el-option label="菜鸟速递" value="菜鸟速递" />
                <el-option label="菜鸟橙运" value="菜鸟橙运" />
                <el-option label="丹鸟物流" value="丹鸟物流" />
              </el-select>
            </el-form-item>

            <el-form-item label="快递单号" required>
              <el-input v-model="shipForm.express_no" placeholder="请输入快递单号" clearable maxlength="50" />
            </el-form-item>
          </el-form>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="closeShipDialog">取消</el-button>
        <el-button type="primary" @click="confirmShip" :loading="shipLoading">确认发货</el-button>
      </div>
    </el-dialog>

    <!-- 物流信息弹窗 -->
    <el-dialog title="物流信息" :visible.sync="logisticsDialogVisible" width="700px" :before-close="handleCloseLogistics">
      <div v-if="currentOrder" class="logistics-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="快递公司">{{ currentOrder.express_company }}</el-descriptions-item>
          <el-descriptions-item label="快递单号">{{ currentOrder.express_no }}</el-descriptions-item>
          <el-descriptions-item label="订单号">{{ currentOrder.order_no }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(currentOrder.status)">
              {{ getStatusText(currentOrder.status) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <div v-if="currentOrder.logisticsData && currentOrder.logisticsData.Traces" class="logistics-tracking">
          <h4>物流跟踪</h4>
          <div class="tracking-list">
            <div 
              v-for="(trace, index) in currentOrder.logisticsData.Traces" 
              :key="index"
              class="tracking-item"
              :class="{ 'tracking-current': index === 0 }"
            >
              <div class="tracking-time">{{ formatDate(trace.AcceptTime) }}</div>
              <div class="tracking-content">
                <div class="tracking-station">{{ trace.AcceptStation }}</div>
                <div class="tracking-location">{{ trace.Location }}</div>
              </div>
            </div>
          </div>
        </div>
        
        <div v-else class="logistics-tracking">
          <h4>物流跟踪</h4>
          <div class="tracking-list">
            <div class="tracking-item">
              <div class="tracking-time">{{ formatDate(currentOrder.created_at) }}</div>
              <div class="tracking-content">订单创建</div>
            </div>
            <div class="tracking-item" v-if="currentOrder.payment_time">
              <div class="tracking-time">{{ formatDate(currentOrder.payment_time) }}</div>
              <div class="tracking-content">订单已付款</div>
            </div>
            <div class="tracking-item" v-if="currentOrder.express_company && currentOrder.express_no">
              <div class="tracking-time">{{ formatDate(currentOrder.updated_at) }}</div>
              <div class="tracking-content">快递公司：{{ currentOrder.express_company }}，单号：{{ currentOrder.express_no }}</div>
            </div>
          </div>
        </div>
        
        <div class="logistics-note">
          <p><strong>说明：</strong>订单通过 {{ currentOrder.express_company }} 快递发货，单号：{{ currentOrder.express_no }}</p>
          <p v-if="currentOrder.logisticsData && currentOrder.logisticsData.DeliveryManTel">
            <strong>快递员电话：</strong>{{ currentOrder.logisticsData.DeliveryManTel }}
          </p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getScOrderList, setScOrdersave, shopinglogistics } from '../../../libs/api'
export default {
  name: 'OrderManagement',
  data() {
    return {
      loading: false,
      orderList: [],
      searchForm: {
        orderNo: '',
        productName: '',
        status: '',
        dateRange: []
      },
      pagination: {
        currentPage: 1,
        pageSize: 20,
        total: 0
      },
      selectedOrders: [],
      orderDetailVisible: false,
      currentOrder: null,
      shipDialogVisible: false,
      logisticsDialogVisible: false,
      shipForm: {
        express_company: '',
        express_no: ''
      },
      shipLoading: false,
      // 统计数据
      orderStats: {
        order_total: 0,
        order_wait: 0,
        order_complete: 0
      }
    }
  },
  computed: {
    totalOrders() {
      return this.orderStats.order_total
    },
    totalAmount() {
      return this.orderList.reduce((sum, order) => {
        return sum + parseFloat(order.pay_amount)
      }, 0).toFixed(2)
    },
    pendingPaymentCount() {
      return this.orderStats.order_wait
    },
    completedCount() {
      return this.orderStats.order_complete
    }
  },
  mounted() {
    this.loadOrderData()
  },
  
  watch: {
    // 监听订单列表变化
    orderList: {
      handler(newVal, oldVal) {
        // 强制更新视图
        this.$nextTick(() => {
          this.forceUpdate()
        })
      },
      deep: true
    },
    
    // 监听当前订单变化
    currentOrder: {
      handler(newVal, oldVal) {
        if (newVal) {
          // 强制更新视图
          this.$nextTick(() => {
            this.forceUpdate()
          })
        }
      },
      deep: true
    }
  },
  methods: {

    // 加载订单数据
    async loadOrderData() {
      this.loading = true
      try {
        // 构建查询参数
        const params = {
          page: this.pagination.currentPage,
          // per_page: this.pagination.pageSize
        }

        // 添加搜索条件
        if (this.searchForm.orderNo) {
          params.order_no = this.searchForm.orderNo
        }
        if (this.searchForm.productName) {
          params.product_name = this.searchForm.productName
        }
        if (this.searchForm.status !== '') {
          params.status = this.searchForm.status
        }
        if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
          params.order_time = `${this.searchForm.dateRange[0]}_${this.searchForm.dateRange[1]}`
        }

        // 调用API
        const res = await getScOrderList(params)

        // 处理API响应数据
        if (res.code === 1) {
          // 处理统计数据
          if (res.data.count && res.data.count.length > 0) {
            const stats = res.data.count[0]
            this.$set(this, 'orderStats', {
              order_total: parseInt(stats.order_total) || 0,
              order_wait: parseInt(stats.order_wait) || 0,
              order_complete: parseInt(stats.order_complete) || 0
            })
          }

          // 使用Vue.set确保数组响应式更新
          this.$set(this, 'orderList', res.data.data || [])
          this.$set(this.pagination, 'total', res.data.total || 0)
          this.$message.success('数据加载成功')
        } else {
          this.$message.error(res.msg || '数据加载失败')
          this.$set(this, 'orderList', [])
          this.$set(this.pagination, 'total', 0)
          // 重置统计数据
          this.$set(this, 'orderStats', {
            order_total: 0,
            order_wait: 0,
            order_complete: 0
          })
        }
      } catch (error) {
        console.error('加载订单数据失败:', error)
        this.$message.error('网络错误，请稍后重试')
        this.orderList = []
        this.pagination.total = 0
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.currentPage = 1
      this.loadOrderData()
    },

    // 重置搜索
    handleReset() {
      // 使用Vue.set确保响应式更新
      this.$set(this.searchForm, 'orderNo', '')
      this.$set(this.searchForm, 'productName', '')
      this.$set(this.searchForm, 'status', '')
      this.$set(this.searchForm, 'dateRange', [])
      this.$set(this.pagination, 'currentPage', 1)
      
      // 强制更新视图
      this.$nextTick(() => {
        this.forceUpdate()
      })
      
      this.loadOrderData()
    },

    // 刷新数据
    refreshData() {
      this.loadOrderData()
    },

    // 强制更新视图
    forceUpdate() {
      this.$forceUpdate()
    },

    // 导出订单
    exportOrders() {
      this.$message.success('订单导出功能开发中...')
    },

    // 查看订单详情
    viewOrderDetail(order) {
      this.currentOrder = order
      this.orderDetailVisible = true
    },

    // 确认付款
    confirmPayment(order) {
      this.$confirm('确认该订单已付款？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 使用Vue.set确保响应式更新
        this.$set(order, 'status', 1)
        this.$message.success('订单状态已更新为已付款')
        // 刷新数据确保视图更新
        this.loadOrderData()
      }).catch(() => { })
    },

    // 发货
    shipOrder(order) {
      this.currentOrder = order
      this.shipDialogVisible = true
    },

    // 确认发货
    async confirmShip() {
      if (!this.shipForm.express_company || !this.shipForm.express_no) {
        this.$message.error('请填写完整的快递信息')
        return
      }

      this.shipLoading = true
      try {
        // console.log(this.currentOrder.id)
        const params = {
          id: this.currentOrder.id,
          status: "2",
          express_company: this.shipForm.express_company,
          express_no: this.shipForm.express_no
        }

        console.log(params)
        const res = await setScOrdersave(params)

        if (res.code === 1) {
          this.$message.success('发货成功')
          this.shipDialogVisible = false
          this.resetShipForm()
          
                  // 立即更新当前订单状态
        if (this.currentOrder) {
          this.$set(this.currentOrder, 'status', '2')
          this.$set(this.currentOrder, 'express_company', this.shipForm.express_company)
          this.$set(this.currentOrder, 'express_no', this.shipForm.express_no)
        }
        
        // 强制更新视图
        this.$nextTick(() => {
          this.forceUpdate()
        })
        
        // 刷新订单数据
        this.loadOrderData()
        } else {
          this.$message.error(res.msg || '发货失败')
        }
      } catch (error) {
        console.error('发货失败:', error)
        this.$message.error('网络错误，请稍后重试')
      } finally {
        this.shipLoading = false
      }
    },

    // 重置发货表单
    resetShipForm() {
      this.shipForm = {
        express_company: '',
        express_no: ''
      }
    },

    // 关闭发货对话框
    closeShipDialog() {
      this.shipDialogVisible = false
      this.resetShipForm()
    },

    // 取消订单
    cancelOrder(order) {
      this.$confirm('确认取消该订单？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 使用Vue.set确保响应式更新
        this.$set(order, 'status', 4)
        this.$message.success('订单已取消')
        // 刷新数据确保视图更新
        this.loadOrderData()
      }).catch(() => { })
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.loadOrderData()
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.loadOrderData()
    },

    // 选择改变
    handleSelectionChange(val) {
      this.selectedOrders = val
    },

    // 关闭订单详情
    handleCloseOrderDetail() {
      this.orderDetailVisible = false
      this.currentOrder = null
    },

    // 查看物流信息
    async viewLogistics(row) {
      try {
        this.currentOrder = row
        this.logisticsDialogVisible = true
        
        // 调用物流查询API
        const res = await shopinglogistics({
          express_company: row.express_company,
          express_no: row.express_no
        })
        
        if (res.code === 1 && res.data.Success) {
          // 使用Vue.set确保响应式更新
          this.$set(this.currentOrder, 'logisticsData', res.data)
        } else {
          this.$message.warning('物流信息查询失败，请稍后重试')
        }
      } catch (error) {
        console.error('查询物流信息失败:', error)
        this.$message.error('查询物流信息失败')
      }
    },

    // 关闭物流信息弹窗
    handleCloseLogistics() {
      this.logisticsDialogVisible = false
      // 清理物流数据，避免下次打开时显示旧数据
      if (this.currentOrder) {
        this.currentOrder.logisticsData = null
      }
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    },

    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        0: 'warning',   // 待付款
        1: 'primary',   // 已付款
        2: 'info',      // 已发货
        3: 'success',   // 已完成
        4: 'danger' ,    // 已取消
        5: 'warning'
      }
      return statusMap[status] || 'info'
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待付款',
        1: '已付款',
        2: '已发货',
        3: '已完成',
        4: '已取消',
        5: '售后'
      }
      return statusMap[status] || '未知'
    },

    // 解析商品规格
    parseSpecs(specsStr) {
      if (!specsStr) return []
      try {
        return JSON.parse(specsStr)
      } catch (error) {
        console.error('解析商品规格失败:', error)
        return []
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.order-management {
  padding: 20px;

  .page-header {
    margin-bottom: 30px;

    h2 {
      margin: 0 0 10px 0;
      color: #303133;
      font-size: 24px;
    }

    p {
      margin: 0;
      color: #909399;
      font-size: 14px;
    }
  }

  .search-section {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
  }

  .stats-section {
    margin-bottom: 20px;

    .stat-card {
      background: #fff;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      display: flex;
      align-items: center;

      .stat-icon {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 20px;

        i {
          font-size: 24px;
          color: #fff;
        }
      }

      .stat-content {
        .stat-number {
          font-size: 24px;
          font-weight: bold;
          color: #303133;
          margin-bottom: 5px;
        }

        .stat-label {
          font-size: 14px;
          color: #909399;
        }
      }
    }
  }

  .order-list {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    // 表格样式优化
    .el-table {
      .el-table__header-wrapper {
        .el-table__header {
          th {
            background: #f8f9fa;
            color: #606266;
            font-weight: 500;
          }
        }
      }

      .el-table__body-wrapper {
        .el-table__row {
          &:hover {
            background: #f5f7fa;
          }
        }
      }
    }

    .list-header {
      padding: 20px;
      border-bottom: 1px solid #ebeef5;
      display: flex;
      justify-content: space-between;
      align-items: center;

      h3 {
        margin: 0;
        color: #303133;
      }

      .list-actions {
        display: flex;
        gap: 10px;
      }
    }

    .product-info {
      display: flex;
      align-items: flex-start;

      .product-image {
        width: 60px;
        height: 60px;
        border-radius: 4px;
        margin-right: 15px;
        flex-shrink: 0;
      }

      .product-details {
        flex: 1;
        min-width: 0;

        .product-name {
          font-weight: 500;
          color: #303133;
          margin-bottom: 8px;
          font-size: 14px;
          line-height: 1.4;
        }

        .product-specs {
          margin-bottom: 8px;

          .spec-item {
            display: inline-block;
            background: #f5f7fa;
            color: #606266;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 12px;
            margin-right: 8px;
            margin-bottom: 4px;
          }
        }

        .product-price {
          margin-bottom: 5px;
          font-size: 13px;

          .price-label,
          .quantity-label {
            color: #909399;
            margin-right: 5px;
          }

          span {
            margin-right: 15px;
          }
        }

        .total-amount {
          color: #f56c6c;
          font-weight: bold;
          font-size: 14px;
        }

        .pay-amount {
          color: #409eff;
          font-weight: bold;
          font-size: 14px;
        }

        .discount-amount {
          color: #67c23a;
          background: #f0f9ff;
          padding: 2px 6px;
          border-radius: 3px;
          border: 1px solid #b3d8ff;
          font-weight: bold;
          font-size: 14px;
        }
      }
    }

    .user-info {

      .user-name,
      .user-mobile,
      .user-remark {
        display: flex;
        align-items: center;
        margin-bottom: 5px;
        font-size: 13px;

        i {
          margin-right: 5px;
          color: #409eff;
        }
      }

      .text-muted {
        color: #909399;
        font-style: italic;
      }
    }

    .address-info {

      .consignee,
      .address-detail,
      .mobile {
        display: flex;
        align-items: center;
        margin-bottom: 5px;
        font-size: 13px;

        i {
          margin-right: 5px;
          color: #67c23a;
        }
      }

      .text-muted {
        color: #909399;
        font-style: italic;
      }
    }

    .status-time {
      margin-top: 5px;
      color: #909399;
      font-size: 12px;
    }

    .pagination-wrapper {
      padding: 20px;
      text-align: center;
      border-top: 1px solid #ebeef5;
    }

    .order-no-container {
      display: flex;
      align-items: center;
      gap: 8px;
      flex-wrap: wrap;

      .group-tag {
        background: linear-gradient(135deg, #ff9a56 0%, #ff6b6b 100%);
        border: none;
        color: #fff;
        font-weight: 500;
        font-size: 10px;
        padding: 2px 6px;
        border-radius: 10px;
        box-shadow: 0 2px 4px rgba(255, 107, 107, 0.3);
        animation: pulse 2s infinite;
      }

      .seckill-tag {
        background: linear-gradient(135deg, #ff4757 0%, #c44569 100%);
        border: none;
        color: #fff;
        font-weight: 500;
        font-size: 10px;
        padding: 2px 6px;
        border-radius: 10px;
        box-shadow: 0 2px 4px rgba(255, 71, 87, 0.3);
        animation: flash 1.5s infinite;
      }
    }

    @keyframes pulse {
      0% {
        box-shadow: 0 2px 4px rgba(255, 107, 107, 0.3);
      }
      50% {
        box-shadow: 0 2px 8px rgba(255, 107, 107, 0.5);
      }
      100% {
        box-shadow: 0 2px 4px rgba(255, 107, 107, 0.3);
      }
    }

    @keyframes flash {
      0%, 100% {
        opacity: 1;
        box-shadow: 0 2px 4px rgba(255, 71, 87, 0.3);
      }
      50% {
        opacity: 0.8;
        box-shadow: 0 2px 8px rgba(255, 71, 87, 0.6);
      }
    }
  }

  .order-detail {
    .detail-card {
      margin-bottom: 20px;

      &:last-child {
        margin-bottom: 0;
      }

      .el-card__header {
        background: #f8f9fa;
        border-bottom: 1px solid #ebeef5;

        span {
          font-weight: 500;
          color: #303133;

          i {
            margin-right: 8px;
            color: #409eff;
          }
        }
      }

      .detail-item {
        display: flex;
        align-items: center;
        margin-bottom: 12px;

        label {
          font-weight: 500;
          color: #606266;
          min-width: 80px;
          margin-right: 10px;
        }

        span {
          color: #303133;
        }

        .order-no {
          font-family: 'Courier New', monospace;
          font-weight: bold;
          color: #409eff;
        }

        .amount {
          font-weight: bold;
          color: #f56c6c;
          font-size: 16px;
        }

        .express-no {
          font-family: 'Courier New', monospace;
          font-weight: 500;
          color: #409eff;
          background: #f0f9ff;
          padding: 2px 8px;
          border-radius: 4px;
          border: 1px solid #b3d8ff;
        }
      }

      .products-list {
        .product-item {
          border: 1px solid #ebeef5;
          border-radius: 8px;
          margin-bottom: 20px;
          overflow: hidden;

          &:last-child {
            margin-bottom: 0;
          }

          .product-header {
            background: #f8f9fa;
            padding: 12px 20px;
            border-bottom: 1px solid #ebeef5;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .product-index {
              font-weight: 500;
              color: #303133;
              font-size: 14px;
            }
          }

          .product-content {
            display: flex;
            padding: 20px;

            .product-image {
              width: 100px;
              height: 100px;
              border-radius: 8px;
              overflow: hidden;
              margin-right: 20px;
              flex-shrink: 0;
              border: 1px solid #ebeef5;
            }

            .product-info {
              flex: 1;

              .product-name {
                margin: 0 0 15px 0;
                color: #303133;
                font-size: 16px;
                font-weight: 500;
              }

              .product-specs {
                margin-bottom: 15px;

                .spec-item {
                  display: inline-block;
                  background: #f5f7fa;
                  color: #606266;
                  padding: 4px 12px;
                  border-radius: 16px;
                  font-size: 12px;
                  margin-right: 10px;
                  margin-bottom: 8px;

                  .spec-label {
                    font-weight: 500;
                    margin-right: 5px;
                  }

                  .spec-value {
                    color: #409eff;
                  }
                }
              }

              .product-price-info {
                .price-row {
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                  margin-bottom: 8px;
                  padding: 8px 0;
                  border-bottom: 1px solid #f0f0f0;

                  &:last-child {
                    border-bottom: none;
                  }

                  .price-label {
                    color: #606266;
                    font-weight: 500;
                    font-size: 14px;
                  }

                  .price-value {
                    color: #303133;
                    font-size: 14px;
                  }

                  &.total-row {
                    background: #f8f9fa;
                    padding: 10px;
                    border-radius: 6px;
                    margin-top: 10px;

                    .total-label {
                      font-weight: 600;
                      color: #303133;
                    }

                    .total-price {
                      font-weight: 600;
                      color: #f56c6c;
                      font-size: 16px;
                    }
                  }
                }
              }
            }
          }
        }

        .order-total {
          background: #f8f9fa;
          border-radius: 8px;
          padding: 20px;
          margin-top: 20px;
          border: 1px solid #ebeef5;

          .total-line {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;

            &:last-child {
              margin-bottom: 0;
            }

            .total-label {
              font-weight: 500;
              color: #606266;
              font-size: 14px;
            }

            .total-amount {
              font-weight: 600;
              color: #f56c6c;
              font-size: 18px;
            }
          }
        }

        .no-products {
          text-align: center;
          padding: 40px 20px;
        }
      }

      .address-detail {
        .detail-item {
          margin-bottom: 15px;

          label {
            min-width: 100px;
          }
        }
      }

      // 发货对话框样式
      .ship-dialog {
        .order-info {
          margin-bottom: 20px;

          .el-descriptions {
            .el-descriptions-item__label {
              font-weight: 500;
              color: #606266;
            }
          }
        }

        .ship-form {
          h4 {
            margin: 0 0 15px 0;
            color: #303133;
            font-size: 16px;
            font-weight: 500;
            border-bottom: 1px solid #ebeef5;
            padding-bottom: 10px;
          }

          .el-form-item {
            margin-bottom: 20px;
          }
        }
      }

      .dialog-footer {
        text-align: right;
      }

      // 物流信息弹窗样式
      .logistics-detail {
        .logistics-tracking {
          margin-top: 20px;

          h4 {
            margin: 0 0 15px 0;
            color: #303133;
            font-size: 16px;
            font-weight: 500;
            border-bottom: 1px solid #ebeef5;
            padding-bottom: 10px;
          }

          .tracking-list {
            .tracking-item {
              display: flex;
              margin-bottom: 15px;
              padding: 15px;
              border: 1px solid #ebeef5;
              border-radius: 6px;
              background: #fafafa;

              &.tracking-current {
                border-color: #409eff;
                background: #ecf5ff;
              }

              .tracking-time {
                min-width: 150px;
                color: #909399;
                font-size: 12px;
                margin-right: 15px;
              }

              .tracking-content {
                flex: 1;

                .tracking-station {
                  font-weight: 500;
                  color: #303133;
                  margin-bottom: 5px;
                }

                .tracking-location {
                  color: #606266;
                  font-size: 12px;
                }
              }
            }
          }
        }

        .logistics-note {
          margin-top: 20px;
          padding: 15px;
          background: #f5f7fa;
          border-radius: 6px;
          border-left: 4px solid #409eff;

          p {
            margin: 0 0 8px 0;
            color: #606266;
            font-size: 14px;

            &:last-child {
              margin-bottom: 0;
            }

            strong {
              color: #303133;
            }
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .order-management {
    padding: 10px;

    .search-section {
      .el-row {
        .el-col {
          margin-bottom: 15px;
        }
      }
    }

    .stats-section {
      .el-row {
        .el-col {
          margin-bottom: 15px;
        }
      }
    }

    .coupon-name {
      color: #e6a23c;
      font-size: 12px;
      font-weight: 500;
      background: #fdf6ec;
      padding: 2px 6px;
      border-radius: 3px;
      border: 1px solid #f5dab1;
    }

    .no-coupon {
      color: #999;
      font-size: 12px;
    }
  }
}
</style>
